package com.pt25.base.model.common.util.compress;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.zip.Deflater;
import java.util.zip.Inflater;

@Configuration
public class FlaterCompressorPoolConfig {

    @Value("${http-configs.max-total:20}")
    private Integer maxTotal;

    @Value("${http-configs.min-idle:4}")
    private Integer minIdle;


    @Bean("deflaterGenericObjectPool")
    public GenericObjectPool<Deflater> deflaterPool() {
        GenericObjectPoolConfig<Deflater> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(minIdle);
        config.setJmxEnabled(false);  // 禁用 JMX
        return new GenericObjectPool<>(new BasePooledObjectFactory<>() {
            @Override
            public Deflater create() {
                return new Deflater();
            }

            @Override
            public PooledObject<Deflater> wrap(Deflater deflater) {
                return new DefaultPooledObject<>(deflater);
            }

            @Override
            public void passivateObject(PooledObject<Deflater> p) {
                p.getObject().reset();
            }
        }, config);
    }

    @Bean("inflaterGenericObjectPool")
    public GenericObjectPool<Inflater> inflaterPool() {
        GenericObjectPoolConfig<Inflater> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(minIdle);
        config.setJmxEnabled(false);  // 禁用 JMX
        return new GenericObjectPool<>(new BasePooledObjectFactory<>() {
            @Override
            public Inflater create() {
                return new Inflater();
            }

            @Override
            public PooledObject<Inflater> wrap(Inflater inflater) {
                return new DefaultPooledObject<>(inflater);
            }

            @Override
            public void passivateObject(PooledObject<Inflater> p) {
                p.getObject().reset();
            }
        }, config);
    }

}
